/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios';
import router from '@/router/index';
import { getToken } from '@/util/auth';
import { Message } from 'element-ui';
// import { baseUrl } from '@/config/env';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { setToken } from '@/util/auth';
//默认超时时间
axios.defaults.timeout = 10000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
//baseUrl
axios.defaults.baseURL = "/api";
// NProgress 配置
NProgress.configure({
  showSpinner: false
});
//http request拦截
axios.interceptors.request.use(config => {
  //开启 progress bar
  NProgress.start();


  if (getToken()) {
    //让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    config.headers['token'] = getToken()
  }
  
  return config
}, error => {
  return Promise.reject(error)
});
//http response 拦截
axios.interceptors.response.use(res => {
  //关闭 progress bar
  NProgress.done();
  //获取状态码
  const status = res.data.code || res.status;
  const message = res.data.errorMsg ||res.data.error|| '未知错误';

  //如果是401则跳转到登录页面
  if (status == 401) {router.push({ path: '/login' })
  
    return Promise.reject(new Error(status))
  }
  if (status == 203) {
    setToken(res.headers.token)
    console.log("res.headers.token",res.headers.token)
  
    return res
  }
  // 如果请求为非200否者默认统一处理
  if (status < 200 ||status >= 300) {
    Message({
      message: message,
      type: 'error'
    });
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
});



export default axios;
